package com.haredot.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.haredot.entity.Order;
import com.haredot.entity.User;
import com.haredot.entity.vo.OrderDetail;
import com.haredot.entity.vo.OrderVo;
import com.haredot.mapper.OrderMapper;
import com.haredot.mapper.UserMapper;
import com.haredot.result.R;
import com.haredot.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper ;

    @Override
    public R<?> applyCoffee(Order order) {

        LocalDateTime applyTime = LocalDateTime.now();

        // 查询 当天领取的次数
        int count = orderMapper.queryApplyCount(order.getApplyUserId(), applyTime) ;

        if (count >= 3) {
            return R.fail("一天内申请次数不允许超过3次").build();
        }

        // 检查 审核人的角色 是否是 教师
        User user = userMapper.selectById(order.getUserId());
        if (user == null || user.getRole() == 1) {
            return R.fail("审核人不正确").build();
        }

        order.setCreateTime(applyTime);
        orderMapper.insert(order);

        return R.ok().build();
    }

    @Override
    public R<?> queryCoffeeList(Long userId, Integer state) {

        List<OrderVo> orders = orderMapper.findCoffeeListByApplyUserId(userId, state) ;
        return R.ok().data(orders);
    }

    @Override
    public R<?> queryOrderDetail(Long cid) {

        OrderDetail orderDetail = orderMapper.findOrderDetail(cid);

        return R.ok().data(orderDetail);
    }

    @Override
    public R<?> confirmOrder(Long cid) {

        // 查看订单是否过期
        Order order = orderMapper.selectById(cid);

        if (order == null) {
            return R.fail("咖啡卷不存在").build();
        }

        if (order.getState() != 2 && order.getState() != 3) {
            return R.fail("咖啡卷状态有误").build() ;
        }

        if (order.getState() == 3) {
            LocalDateTime overTime = order.getOverTime();
            return R.fail("咖啡卷已使用、使用时间为" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(overTime)).build();
        }

        if (order.getEffectTime().isBefore(LocalDate.now())) {
            return R.fail("咖啡卷已过期").build();
        }
        // 修改咖啡卷的状态 为已完成
        orderMapper.update(new LambdaUpdateWrapper<Order>()
                .set(Order::getState , 3)
                .set(Order::getOverTime, LocalDateTime.now())
                .eq(Order::getId, cid)
                .eq(Order::getState, 2));

        return R.ok().build();
    }
}
